package com.ideaction.game.bus.doctor;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ideaction.game.bus.BIOrder;
import com.ideaction.game.bus.OrderType;
import com.ideaction.game.utils.MD5;
import com.ideaction.game.xmldata.SampleContainer;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @author ZGame 配置热更 orderId 1
 *
 */
@Slf4j
@Component
public class XmlConfigHotFix implements OrderType {
	@Value("${xmldata.config}")
	private String xmldataConfig;// xml
	@Autowired
	private SampleContainer<?> sampleContainer;

	@Override
	public int getOrderId() {
		return 1;
	}

	@Override
	public void action(BIOrder bIOrder) {

		try {
			String content = bIOrder.getContent();
			JSONObject jsonObj = JSON.parseObject(content);
			String className = jsonObj.getString("className");
			String xmlName = jsonObj.getString("xmlName");
			String xmlContent = jsonObj.getString("xmlContent");
			File file = new File(xmldataConfig + File.separator + xmlName);
			if (!file.exists()) {
				log.info("找不到配置表 xmlName:" + xmlName + " className:" + className);
				return;
			}
			// 对比一下内容
			String upKey = MD5.MD5Encode(xmlContent);
			FileReader fileReader = new FileReader(file);
			StringBuffer buffer = new StringBuffer();
			char[] buf = new char[1024];
			int len;
			while ((len = fileReader.read(buf)) != -1) {
				buffer.append(new String(buf, 0, len));
			}
			fileReader.close();
			String oldContent = buffer.toString();
			String oldKey = MD5.MD5Encode(oldContent);
			if (upKey.equals(oldKey)) {
				log.info("配置内容没有变化 xmlName:" + xmlName + " className:" + className);
				// return;
			}
			FileWriter writer = new FileWriter(file);
			writer.write(xmlContent);
			writer.flush();
			writer.close();
			log.info("配置表写入完毕: className:" + className);
			sampleContainer.reload(xmldataConfig,xmlName);

			log.info("配置表热更完毕: className:" + className);
		} catch (IllegalArgumentException | IOException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		}
	}

}
